# src/api/artwork_api.py
from flask import Blueprint, request, jsonify
from src.service.artwork_service import publish_artwork, get_artwork_list, get_artwork_detail
from src.utils.logger import get_logger

artwork_bp = Blueprint("artwork", __name__, url_prefix="/api/artwork")
logger = get_logger(__name__)

@artwork_bp.route("/publish", methods=["POST"])
def publish():
    """卖家发布艺术品接口"""
    try:
        data = request.get_json()
        title = data.get("title")
        description = data.get("description", "")
        price = data.get("price")
        creator = data.get("creator")
        owner_id = data.get("owner_id")
        category = data.get("category", "")
        era = data.get("era", "")
        
        # 调用业务逻辑
        artwork_id, msg = publish_artwork(
            title=title,
            description=description,
            price=price,
            creator=creator,
            owner_id=owner_id,
            category=category,
            era=era
        )
        
        if artwork_id:
            return jsonify({
                "success": True,
                "message": msg,
                "artwork_id": artwork_id
            }), 201
        else:
            return jsonify({"success": False, "error": msg}), 400
    except Exception as e:
        logger.error(f"发布艺术品接口异常：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500

@artwork_bp.route("/list", methods=["GET"])
def get_list():
    """获取艺术品列表（支持筛选）"""
    try:
        # 从URL参数获取筛选条件
        category = request.args.get("category")
        era = request.args.get("era")
        keyword = request.args.get("keyword")
        
        # 调用业务逻辑
        artworks = get_artwork_list(category=category, era=era, keyword=keyword)
        
        return jsonify({
            "success": True,
            "count": len(artworks),
            "artworks": artworks
        }), 200
    except Exception as e:
        logger.error(f"获取艺术品列表接口异常：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500

@artwork_bp.route("/<int:artwork_id>", methods=["GET"])
def get_detail(artwork_id):
    """获取艺术品详情"""
    try:
        artwork, msg = get_artwork_detail(artwork_id)
        
        if artwork:
            return jsonify({
                "success": True,
                "artwork": artwork
            }), 200
        else:
            return jsonify({"success": False, "error": msg}), 404
    except Exception as e:
        logger.error(f"获取艺术品详情接口异常：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500